package com.rzjm.exercise.module.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzjm.exercise.common.base.controller.BaseController;
import com.rzjm.exercise.common.base.data.DataTableLayUI;
import com.rzjm.exercise.common.log.annotation.Log;
import com.rzjm.exercise.common.utils.R;
import com.rzjm.exercise.module.domain.*;
import com.rzjm.exercise.module.service.*;
import com.rzjm.exercise.sys.system.user.domain.UserDO;
import lombok.val;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 片区
 *
 * @author mr.zhou
 * @email zhouwei_nice@163.com
 * @date 2020-12-15 22:36:23
 */
@Controller
@RequestMapping("/module/pianqu")
public class PianqusController extends BaseController {
    @Resource
    private PianqusService pianqusService;
    @Resource
    private GroupsService groupsService;
    @Resource
    private DeviceWeldingService deviceWeldingService;
    @Resource
    private DeviceNodeService deviceNodeService;
    @Resource
    private DeviceService deviceService;
    @Resource
    private ShopService shopService;
    @Resource
    private TemperatureLimitService temperatureLimitService;


    @Log("查询片区页面")
    @GetMapping()
    @RequiresPermissions("module:pianqu:pianqu")
    String Shop() {
        return "module/pianqu/pianqu";
    }

    @Log("查询片区")
    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("module:pianqu:pianqu")
    public DataTableLayUI<Pianqus> list(DataTableLayUI<Pianqus> condition) {
        UserDO user = getUser();
        if(user.getUserType() > 1){//集团用户
            QueryWrapper<Pianqus> qw = new QueryWrapper<>();
            qw.eq("jituan_id",user.getGroupId());
            condition.setQw(qw);
        }
        DataTableLayUI<Pianqus> dt = pianqusService.pageSearchLayUI(condition);
        List<Pianqus> list = dt.getData();
        if(CollUtil.isNotEmpty(list)){
            list.forEach(pianqu->{
                Groups groups = groupsService.findById(pianqu.getJituanId());
                if(groups!=null){
                    pianqu.setJituanName(groups.getGroupName());
                }
            });
        }
        return dt;
    }

    @Log("新增片区页面")
    @GetMapping("/add")
    @RequiresPermissions("module:pianqu:add")
    String add(Model model) {
        UserDO user = getUser();
        Pianqus pianqu = new Pianqus();
        QueryWrapper<Groups> qw = new QueryWrapper<>();
        if(user.getUserType() > 1){
            qw.eq("id",user.getGroupId());
        }else{
            qw.gt("id",1);
        }
        List<Groups> groups = groupsService.list(qw);
        model.addAttribute("pianqu", pianqu);
        model.addAttribute("groups", groups);
        return "module/pianqu/detail";
    }

    @Log("编辑片区页面")
    @GetMapping("/edit/{id}")
    @RequiresPermissions("module:pianqu:edit")
    String edit(@PathVariable("id") Integer id, Model model) {
        UserDO user = getUser();
        Pianqus pianqu = pianqusService.findById(id);
        QueryWrapper<Groups> qw = new QueryWrapper<>();
        if(user.getUserType() > 1){
            qw.eq("id",user.getGroupId());
        }else{
            qw.gt("id",1);
        }
        List<Groups> groups = groupsService.list(qw);
        model.addAttribute("groups", groups);
        model.addAttribute("pianqu", pianqu);
        return "module/pianqu/detail";
    }


    @PostMapping(value = "/getPianquDeviceTypeChart")
    @ResponseBody
    public R getTownDeviceTypeChart(Integer type) {
        UserDO user = getUser();

        Map<String,Object> map = new HashMap<>();
        List<Pianqus> pianquList = pianqusService.selectListByColumn("jituan_id",user.getGroupId());
        List<Integer> device0Count = new ArrayList<>();
        List<Integer> device1Count = new ArrayList<>();

        List<String> pianquNames = new ArrayList<>();
        for (Pianqus pianqu : pianquList){

            pianquNames.add(pianqu.getPianquName());

            Map<String,Object> map0 = new HashMap<>();
            map0.put("group_id", user.getGroupId());
            map0.put("pianqu_id", pianqu.getId());
            map0.put("device_type",0);
            Integer weldingCount0 = deviceWeldingService.getDeviceCountByUserId(map0);
            device0Count.add(weldingCount0);


            Map<String,Object> map1 = new HashMap<>();
            map0.put("group_id", user.getGroupId());
            map1.put("pianqu_id", pianqu.getId());
            map1.put("device_type",1);
            Integer weldingCount1 = deviceWeldingService.getDeviceCountByUserId(map1);
            device1Count.add(weldingCount1);
        }

        map.put("pianquName", pianquNames);
        map.put("device0Count", device0Count);
        map.put("device1Count", device1Count);


//        QueryWrapper<TemperatureLimit> qwLimit = new QueryWrapper<>();
//        qwLimit.eq("group_id", user.getGroupId());
//        List<TemperatureLimit> limits = temperatureLimitService.list(qwLimit);
//
//        List<Map<String, Object>> tempDeviceList = new ArrayList<>();
//        int count_0 = 0, count_1 = 0, count_2 = 0;
//        List<Shop> shops = shopService.selectListByColumn("group_id", user.getGroupId());
//        for (Shop shop : shops){
//
//            if(shop.getDeviceShowType() == 0){//显示的是设备数
//                int count0 = 0,count1 = 0,count2 = 0;
//                QueryWrapper<Device> qwDevice = new QueryWrapper<>();
//                qwDevice.eq("shop_id", shop.getId());
//                List<Device> deviceList = deviceService.list(qwDevice);
//                for(Device device : deviceList){
//                    QueryWrapper<DeviceNode> qwNode = new QueryWrapper<>();
//                    qwNode.eq("device_id", device.getId());
//                    qwNode.eq("device_type", 2);
//                    List<DeviceNode> nodes = deviceNodeService.list(qwNode);
//                    for (DeviceNode node : nodes){
//
//                        if(node.getCurrentValue()  > 0 && node.getCurrentValue() < 50){
//                            count_0 += 1;
//                            count0++;
//                        }else if(node.getCurrentValue() >= 50 && node.getCurrentValue() <= 70){
//                            count_1 += 1;
//                            count1++;
//                        }else if(node.getCurrentValue() > 70){
//                            count_2 += 1;
//                            count2++;
//                        }
//                    }
//                }
//                System.out.println(" 显示设备数的： "+shop.getShopName() + ": count_0 = " + count0 + ", count_1 = " + count1+ ", count_2 = " + count2);
//            }else{
//                QueryWrapper<DeviceNode> qwNode0 = new QueryWrapper<>();
//                qwNode0.eq("device_type", 2);
//                qwNode0.eq("shop_id", shop.getId());
//                qwNode0.lt("current_value", 50);
//                qwNode0.gt("current_value", 0);
//                long countNode0 = deviceNodeService.count(qwNode0);
//                count_0 += countNode0;
//
//                QueryWrapper<DeviceNode> qwNode1 = new QueryWrapper<>();
//                qwNode1.eq("shop_id", shop.getId());
//                qwNode1.eq("device_type", 2);
//                qwNode1.between("current_value", 50,70);
//                long countNode1 = deviceNodeService.count(qwNode1);
//                count_1 += countNode1;
//
//                QueryWrapper<DeviceNode> qwNode2 = new QueryWrapper<>();
//                qwNode2.eq("shop_id", shop.getId());
//                qwNode2.eq("device_type", 2);
//                qwNode2.gt("current_value", 70);
//                long countNode2 = deviceNodeService.count(qwNode2);
//                count_2 += countNode2;
//                System.out.println(" 显示设备节点数的： "+shop.getShopName() + ": count_0 = " + countNode0 + ", count_1 = " + countNode1+ ", count_2 = " + countNode2);
//            }
//        }
//
//
//        Map<String, Object> map0 = new HashMap<>();
//        map0.put("value", count_0);
//        map0.put("name", "50摄氏度以下");
//
//
//        Map<String, Object> map1 = new HashMap<>();
//        map1.put("value", count_1);
//        map1.put("name", "50~70摄氏度");
//
//
//        Map<String, Object> map2 = new HashMap<>();
//        map2.put("value", count_2);
//        map2.put("name", "70摄氏度以上");
//
//        tempDeviceList.add(map0);
//        tempDeviceList.add(map1);
//        tempDeviceList.add(map2);
//        map.put("tempDeviceList",tempDeviceList);

        Map<String,Object> mapTemp = getTempChart();

        map.putAll(mapTemp);;
        return R.ok(map);
    }


    private Map<String, Object> getTempChart(){

        UserDO user = getUser();

        List<Shop> shops = shopService.selectListByColumn("group_id", user.getGroupId());

        Map<String,Object> map = new HashMap<>();

        List<Map<String, Object>> tempDeviceList = new ArrayList<>();

        QueryWrapper<TemperatureLimit> qwLimit = new QueryWrapper<>();
        qwLimit.eq("group_id", user.getGroupId());
        List<TemperatureLimit> limits = temperatureLimitService.list(qwLimit);
        for (TemperatureLimit limit : limits){
            int count = 0;
            for (Shop shop : shops){
                if(shop.getDeviceShowType() == 0){//显示的是设备数
                    QueryWrapper<Device> qwDevice = new QueryWrapper<>();
                    qwDevice.eq("shop_id", shop.getId());
                    List<Device> deviceList = deviceService.list(qwDevice);
                    for(Device device : deviceList){
                        QueryWrapper<DeviceNode> qwNode = new QueryWrapper<>();
                        qwNode.eq("device_id", device.getId());
                        qwNode.eq("device_type", 2);
                        List<DeviceNode> nodes = deviceNodeService.list(qwNode);
                        for (DeviceNode node : nodes){

                            if(limit.getIsRange() == 0 && node.getCurrentValue() < limit.getMinValue()){
                                count += 1;
                            } else if(limit.getIsRange() == 1 && node.getCurrentValue() >= limit.getMinValue() && node.getCurrentValue() <= limit.getMaxValue()){
                                count += 1;
                            } else if(limit.getIsRange() == 2 && node.getCurrentValue() > limit.getMinValue()){
                                count += 1;
                            }
                        }
                    }
//                    System.out.println(" 显示设备数的： "+shop.getShopName() + ": count_0 = " + count0 + ", count_1 = " + count1+ ", count_2 = " + count2);
                }else{
                    QueryWrapper<DeviceNode> qwNode0 = new QueryWrapper<>();
                    qwNode0.eq("device_type", 2);
                    qwNode0.eq("shop_id", shop.getId());
                    //是否是范围值 0 - 小于等于  1 - 范围值  2 - 大于等于
                    if(limit.getIsRange() == 0){
//                        qwNode0.gt("current_value", limit.getMinValue());
                        qwNode0.lt("current_value", limit.getMinValue());
                    } else if(limit.getIsRange() == 1){
                        qwNode0.between("current_value", limit.getMinValue(),limit.getMaxValue());
                    } else if(limit.getIsRange() == 2){
                        qwNode0.gt("current_value", limit.getMinValue());
                    }
                    long countNode0 = deviceNodeService.count(qwNode0);
                    count += countNode0;
//                    System.out.println(" 显示设备节点数的： " + shop.getShopName() + ": count_0 = " + countNode0 + ", count_1 = " + countNode1+ ", count_2 = " + countNode2);
                }
            }

            Map<String, Object> map0 = new HashMap<>();
            map0.put("value", count);
            //是否是范围值 0 - 小于等于  1 - 范围值  2 - 大于等于
            if(limit.getIsRange() == 0){
                map0.put("name", limit.getMinValue() + "摄氏度以下");
            } else if(limit.getIsRange() == 1){
                map0.put("name", limit.getMinValue() + "~" + limit.getMaxValue() + "摄氏度");
            } else if(limit.getIsRange() == 2){
                map0.put("name", limit.getMinValue() + "摄氏度以上");
            }
            map0.put("limitId", limit.getId());
            tempDeviceList.add(map0);
        }

        map.put("limitList",limits);
        map.put("tempDeviceList",tempDeviceList);

        return map;
    }


    /**
     * 保存
     */
    @Log("新增片区")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("module:pianqu:add")
    public R save(@Valid Pianqus pianqu) {
        if (pianqusService.save(pianqu)) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @Log("更新片区")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("module:pianqu:edit")
    public R update(@Valid Pianqus pianqu) {
        pianqusService.updateById(pianqu);
        return R.ok();
    }

    /**
     * 删除
     */
    @Log("删除片区")
    @PostMapping( "/remove")
    @ResponseBody
    @RequiresPermissions("module:pianqu:remove")
    public R remove( Integer id) {
        if (pianqusService.removeById(id)) {
            return R.ok();
        }
        return R.error();
    }
}
